var express = require('express');
const stureturn = express.Router();
var bodyParser = require('body-parser');
const path = require("path");
const Database = require("better-sqlite3");
//获取数据库中管理员账号密码等信息
const mydb = new Database(path.resolve(__dirname, "../database/infor.db"), { verbose: console.log });

// 创建 application/x-www-form-urlencoded 编码解析
stureturn.use(bodyParser.urlencoded({ extended: false }))
stureturn.use(express.json());
stureturn.use(bodyParser.json());

stureturn.post('/stureturn', function (req, res) {
    // 获取前端数据
    var response = {
        "code": req.body.code,
        "stu_id": req.body.stu_id
    };
    //指定数据库文件路径
    const bookcode = mydb.prepare('SELECT * FROM lend WHERE code= ? and stuid=? and state=? order by lend_num desc limit 0,1 ');//一个查询语句对象
    var a = bookcode.get(response.code, response.stu_id, "no");//执行查询
    if (a) {
        // 如果查询到了
        // 先判断图书是否逾期，如果逾期了，就要登记在罚款单上---fine
        // 先获取当前时间，和 due 字段对比
        var date = new Date();
        var t1 = date.getTime();
        var t2 = new Date(a.due).getTime();
        // console.log(t1);
        // console.log(t2);
        if (t1 > t2) {
            // 说明逾期了，要登记罚款单
            // 计算罚款金额
            var money = ((t1 - t2) * 0.000000000006).toFixed(2);
            // 找到这个学生的id
            const updata_book = mydb.prepare('UPDATE fine SET money =money+@money,state=@state  WHERE stuid=@stuid');
            updata_book.run({ money: money, state: "no", stuid: response.stu_id });

        }
        // 在book表中把现存量加上去---book
        const updata_book = mydb.prepare('UPDATE book SET inventory =inventory+1  WHERE code=@code');
        updata_book.run({ code: response.code });
        // 在lend表中把state修改为已还---yes
        const updata_lend = mydb.prepare('UPDATE lend SET state =@state WHERE code= @code and stuid=@stuid order by lend_num desc limit 0,1');
        updata_lend.run({ state: "yes", code: response.code, stuid: response.stu_id });
        res.sendFile(path.resolve(__dirname, "../public/html/return_success.html"));
    }
    else {
        // 如果没有查询到，说明这本书不存在
        console.log("该书不存在");
        res.sendFile(path.resolve(__dirname, "../public/html/return_error.html"));
    }
});

module.exports = stureturn;